package com.xing.lei.happy.thrid.flh.sql.utils;

import com.xing.lei.happy.thrid.flh.sql.enums.SqlType;

import java.util.regex.Pattern;

public class SqlTypeRecognizer {
    public static SqlType recognize(String sql) {
        String s = sql.trim().toUpperCase();
        
        // INSERT INTO
        if (Pattern.compile("INSERT\\s+INTO", Pattern.CASE_INSENSITIVE).matcher(s).find()) {
            return SqlType.INSERT;
        }

        // ALTER TABLE ADD PRIMARY KEY
        Pattern addPkPat = Pattern.compile("ALTER\\s+TABLE\\s+[a-zA-Z0-9_]+\\s+ADD\\s+PRIMARY\\s+KEY", Pattern.CASE_INSENSITIVE);
        if (addPkPat.matcher(s).find()) {
            return SqlType.ADD_PRIMARY_KEY;
        }

        // ALTER TABLE ADD COLUMN
        Pattern addColPat = Pattern.compile("ALTER\\s+TABLE\\s+[a-zA-Z0-9_]+\\s+ADD\\s+[^,\\s]+", Pattern.CASE_INSENSITIVE);
        if (addColPat.matcher(s).find()) {
            return SqlType.ADD_COLUMN;
        }

        // ALTER TABLE MODIFY 或 ALTER COLUMN
        Pattern modColPat = Pattern.compile("ALTER\\s+TABLE\\s+[a-zA-Z0-9_]+\\s+(MODIFY|ALTER\\s+COLUMN)", Pattern.CASE_INSENSITIVE);
        if (modColPat.matcher(s).find()) {
            return SqlType.MODIFY_COLUMN;
        }

        // UPDATE
        Pattern updatePat = Pattern.compile("UPDATE\\s+[a-zA-Z0-9_]+\\s+SET", Pattern.CASE_INSENSITIVE);
        if (updatePat.matcher(s).find()) {
            return SqlType.UPDATE;
        }

        // CREATE TABLE
        Pattern createTablePat = Pattern.compile("CREATE\\s+TABLE\\s+[a-zA-Z0-9_]+", Pattern.CASE_INSENSITIVE);
        if (createTablePat.matcher(s).find()) {
            return SqlType.CREATE_TABLE;
        }

        // CREATE INDEX / CREATE UNIQUE INDEX
        Pattern createIndexPat = Pattern.compile("CREATE(\\s+UNIQUE)?\\s+INDEX\\s+[a-zA-Z0-9_]+", Pattern.CASE_INSENSITIVE);
        if (createIndexPat.matcher(s).find()) {
            return SqlType.CREATE_INDEX;
        }

        return SqlType.UNKNOWN;
    }
} 